package org.fight.landowner.common;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author wangxuehao02
 * @Date 2024/2/27 8:04 PM
 * @Description
 *
 * 延迟执行任务，到期执行从队列弹出后执行回调
 **/

@Slf4j
public class DelayExecuteTaskQueue extends DelayQueue<DelayTask> {

    private Thread executeThread;

    private DelayExecuteTaskActuator delayExecuteTaskActuator;

    private String executeThreadName;

    private AtomicBoolean isStart = new AtomicBoolean(false);

    public DelayExecuteTaskQueue(String executeThreadName, DelayExecuteTaskActuator delayExecuteTaskActuator) {
        this.executeThreadName = executeThreadName;
        this.delayExecuteTaskActuator = delayExecuteTaskActuator;
    }

    public void start() {
        if (isStart.compareAndSet(false, true)) {
            executeThread = new Thread(() -> {
                while (isStart.get()) {
                    try {
                        DelayTask delayTask = this.take();

                        delayExecuteTaskActuator.execute(delayTask);
                    } catch (Exception e) {
                        log.error("DelayExecuteTaskQueue {} execute error = {}", executeThreadName, e);
                    }
                }
            }, executeThreadName);

            executeThread.start();
        }
    }

    public void stop() {
        isStart.set(false);
    }

    public interface DelayExecuteTaskActuator<E extends DelayTask> {
        void execute(E delayTask);
    }
}
